package io.github.liuyuhao412.manager.config;

import javax.security.sasl.AuthenticationException;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import io.github.liuyuhao412.manager.exception.codeException;
import io.github.liuyuhao412.manager.request.ApiResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {
	// 登录异常
	@ExceptionHandler(codeException.class)
	public ApiResponse<String> codeFailed(codeException ex) {
		return ApiResponse.error(-1, ex.getMessage());
	}

	// 捕获唯一约束异常（用户名重复）
	@ExceptionHandler(DuplicateKeyException.class)
	public ApiResponse<String> handleDuplicateKeyException(DuplicateKeyException ex) {
		String msg = ex.getMessage();
		if (msg.contains("user.username")) {
			return ApiResponse.error(-1, "用户名已存在");
		} else {
			return ApiResponse.error(-1, "数据重复");
		}
	}

	// Spring Security 权限不足
	@ExceptionHandler(AccessDeniedException.class)
	public ApiResponse<String> handleAccessDeniedException(AccessDeniedException ex) {
		return ApiResponse.error(403, "权限不足");
	}

	// Spring Security 认证失败
	@ExceptionHandler(AuthenticationException.class)
	public ApiResponse<String> handleAuthenticationException(AuthenticationException ex) {
		return ApiResponse.error(401, "未认证或认证失败");
	}

	@ExceptionHandler(Exception.class)
	public ApiResponse<String> handleException(Exception ex) {
		return ApiResponse.error(-1, "服务器内部错误");
	}
}